package com.recharge.sup.impl;


import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.recharge.OrderService;
import com.recharge.domain.Province;
import com.recharge.domain.TradeFlow;
import com.recharge.domain.TradeOrder;
import com.recharge.domain.TradeSupProductInfo;
import com.recharge.mapper.IProvinceMapper;
import com.recharge.mapper.ITradeOrderMapper;
import com.recharge.mapper.ITradeSupProductInfoMapper;
import com.recharge.sup.AbsSupChargeService;
import com.recharge.utils.HttpClientUtils;
import com.recharge.utils.ProcessResult;
import com.recharge.utils.ResultCodeQuXun;
import com.recharge.utils.ValueConvertUtils;


/**
 * 趣讯对接
 * @author qq
 *
 */
@Service
public class QuXunChargeServiceImpl extends AbsSupChargeService{
	
	//合作方编号
	@Value("${quxun.partnerNo}")
    private String partner_no ;
	//合同id
    @Value("${quxun.contractId}")
    private String contract_id ;
    
    @Value("${quxun.queryOrderUrl}")
    private String queryOrderUrl ;
    
    @Value("${quxun.sendFlowUrl}")
    private String sendFlowUrl ;
    
    @Value("${quxun.queryStatusUrl}")
    private String queryStatusUrl ;
    
    @Value("${quxun.queryBanlanceUrl}")
    private String queryBanlanceUrl ;
    
    @Value("${quxun.queryCallBackUrl}")
    private String back_url ;
    
    @Value("${quxun.key}")
    private String key ;
    
    @Value("${quxun.iv}")
    private String iv;
	
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private IProvinceMapper iProvinceMapper;
    
    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;
    
    @Autowired
    private ResultCodeQuXun resultCodeQuXun;
    
    @Autowired
    private ITradeSupProductInfoMapper iTradeSupProductInfoMapper;

    private Logger logger = LoggerFactory.getLogger(getClass());
    
    /**
     * 订单充值
     */
	@Override
	public ProcessResult recharge(TradeOrder tradeOrder, TradeFlow tradeFlow) {
		String request_no = tradeOrder.getOrderId();  //请求编号(订单号)
		String order_id = tradeOrder.getOrderId();    //订单id(和request_no一致)
		String phone_id = tradeOrder.getChargeNumber();    //手机号码
		String facevalue = String.valueOf(tradeOrder.getFaceValue());   //面值
		String timestamp = String.valueOf(System.currentTimeMillis()/1000);//时间戳
//		Short isp_id = tradeOrder.getIspId();  //省份
//		Long charge_money = tradeOrder.getChargeMoney();//流量值
		
		
        
		
	    //查询趣讯的商品
		String productname = tradeOrder.getProduct();
	    TradeSupProductInfo quxun= iTradeSupProductInfoMapper.selectToChannel(productname,"quxun");
	    String plat_offer_id = null;
	    if(quxun != null &&!"".equals(quxun)){
	    	plat_offer_id = quxun.getChannelProductId();
	    	logger.info("查询到趣讯productid:{}", plat_offer_id);
	    }else{
	    	logger.info("没有查询到趣讯商品");
	    	ProcessResult processResult = new ProcessResult();
	    	processResult.setCode(ProcessResult.FAIL);
        	return processResult;
	    }
	   // 充值
		Map<String, String> keyParams = new HashMap<String, String>();
		keyParams.put("contract_id", contract_id);
		keyParams.put("facevalue", facevalue);
		keyParams.put("order_id", order_id);
		keyParams.put("plat_offer_id", plat_offer_id);
		keyParams.put("phone_id", phone_id);
		keyParams.put("request_no", request_no);
		keyParams.put("timestamp", timestamp);
		keyParams.put("back_url", back_url);
		
		String keyParamsStr =JSON.toJSONString(keyParams);//转成json
		
	    String code = null;
		try {
			code = encrypt(keyParamsStr,key,iv);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	    Map<String, String> sendParams = new HashMap<String, String>();
	    sendParams.put("partner_no", partner_no);
	    sendParams.put("code", code);
	    String sendParamsJson = JSON.toJSONString(sendParams);//转成json
	    StringEntity strParams = new StringEntity(sendParamsJson, "UTF-8");//转成StringEntity
	    String result = null;
	    try {
	    	logger.info("发送趣讯请求：{}",sendFlowUrl + "参数：" + sendParamsJson);
	    	result =HttpClientUtils.invokePostString(sendFlowUrl, strParams, "UTF-8", 3000);
    	} catch (Exception e) {
    		logger.error("充值趣讯接口异常",e);
    	}
	    if(result != null && !"".equals(result)){
	    	Map<String, String> resMap = jsonToObject(result);
	    	String orderstatus = resMap.get("orderstatus"); //订单状态
	    	String result_code = resMap.get("result_code"); //结果编码
	    	ProcessResult processResult = new ProcessResult();//实例化处理结果类
	    	String resultCode = resultCodeQuXun.processResultCode(result_code);
            if ("processing".equals(orderstatus)) {      //发送成功 ,等待回调
            	iTradeOrderMapper.updateProcessStatus(order_id, resultCode);
                logger.info("orderid : {}订单发送成功,result_code：{}",order_id,resultCode);
                processResult.setCode(ProcessResult.PROCESSING);
                return processResult;
            }else if("fail".equals(orderstatus)){        //发送失败
            	iTradeOrderMapper.updateProcessStatus(order_id, resultCode);
            	logger.info("发送失败orderid:{},原因result_code：{}",order_id,resultCode);
            	processResult.setCode(ProcessResult.FAIL);
            	return processResult;
            }
	    }
	    iTradeOrderMapper.updateProcessStatus(order_id,"发送失败");
	    logger.info("order_id:{}发送结果可疑",order_id );        
        ProcessResult processResult = new ProcessResult();
        processResult.setCode(ProcessResult.UNKNOWN);   
        return processResult;                        
	}



	/**
	 * 订单查询
	 */
	@Override
	public ProcessResult query(TradeOrder tradeOrder, TradeFlow tradeFlow) {
		ProcessResult processResult = new ProcessResult();
		String request_no = tradeOrder.getOrderId();
		Map<String, String> params = new HashMap<String, String>();
		params.put("request_no",request_no);
		params.put("partner_no",partner_no);
		params.put("contract_id",contract_id);
		String paramsJson = JSON.toJSONString(params);  //map转json
		StringEntity strParams = new StringEntity(paramsJson,"UTF-8");//json转StringEntity
		String result = null;
		try {
		    logger.info("查询趣讯订单状态请求：{}",queryStatusUrl + "参数：" + paramsJson);
		    result =HttpClientUtils.invokePostString(queryStatusUrl, strParams, "UTF-8", 3000); 
	    } catch (Exception e) {
	    	logger.error("查询趣讯订单接口异常",e);
	    }
		if (result != null && !"".equals(result)) {
			Map<String, String> rspMap = jsonToObject(result);
            String result_code = rspMap.get("result_code");
            String orderstatus = rspMap.get("orderstatus");
            String resultCode = resultCodeQuXun.processResultCode(result_code);     
            if( !"5007".equals(result_code)){  //返回结果不为5007
            	iTradeOrderMapper.updateProcessStatus(request_no,resultCode);
            	if("finish".equals(orderstatus)){	
            		logger.info("orderid : {}订单成功",request_no);
                	processResult.setCode(ProcessResult.SUCCESS);
                	return processResult;
            	}else if("fail".equals(orderstatus)){
            		logger.info("orderid : {}订单失败,原因result_code：{}",request_no,resultCode);
            		processResult.setCode(ProcessResult.FAIL);
            		return processResult;
            	}else if("processing".equals(orderstatus)){
            		logger.info("orderid : {}订单正在处理中",request_no);
            		processResult.setCode(ProcessResult.PROCESSING);
            		return processResult;
            	}
            }else if("5007".equals(result_code)){
            	iTradeOrderMapper.updateProcessStatus(request_no,"订单不存在");
            	logger.info("orderid : {}订单不存在",request_no);
        		processResult.setCode(ProcessResult.FAIL);
        		return processResult;
            }
		}
	   // 结果为空就设置未知
		logger.info("orderid : {}订单查询可疑",request_no);
        processResult.setCode(ProcessResult.UNKNOWN);
        return  processResult;
	}
		
	/**
	 * 回调
	 */
	@Override
	public void response(TradeOrder tradeOrder, TradeFlow tradeFlow, Map<String, String> responseMap) {
       String orderstatus  = responseMap.get("orderstatus");
       if (StringUtils.equals("finish",orderstatus )){     
           orderService.SUCCESS(tradeOrder,tradeFlow);
       }else if (StringUtils.equals("fail",orderstatus )){
           orderService.FAIL(tradeOrder, tradeFlow); 
       }else{
           orderService.UNKNOWN(tradeOrder, tradeFlow);//调用unkown方法
       }
	}

	
	/**
	 * 加密
	 */
	 public static String encrypt(String input, String key, String vi) throws Exception { 
		 try {             
			 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
			 cipher.init(Cipher.ENCRYPT_MODE, 
					 new SecretKeySpec(key.getBytes(), "AES"), 
					 new IvParameterSpec(vi.getBytes())); 
			 byte[] encrypted = cipher.doFinal(input.getBytes("utf-8")); 
			// 此处使用 BASE64 做转码。             
			 return DatatypeConverter.printBase64Binary(encrypted); 
		 } catch (Exception ex) {             
			 return null; 
		 } 
	 }
	 
	 /**
	  * json字符串转Map
	  */
	 public static Map<String,String> jsonToObject(String jsonStr){
	      Map<String, String> map = new HashMap<String, String>();
	      map= (Map<String, String>) JSON.parseObject(jsonStr, HashMap.class);
	      return map;
	 }
	 
	 public static void main(String[] args) {
		 String productTemplate = "运营商_流量值_全国通用流量";
		 Short i = 2;
         String productName = productTemplate.replace("运营商", ValueConvertUtils.ispMapper.get((short)i))
                 .replace("流量值", 100 + "M")
                 .replace("_", "");
         System.out.println(productName);
	}
}
